/*
 * Copyright (c) 2008-2010, Matthias Mann All rights reserved. Redistribution
 * and use in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met: * Redistributions
 * of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer. * Redistributions in binary form
 * must reproduce the above copyright notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided
 * with the distribution. * Neither the name of Matthias Mann nor the names of
 * its contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission. THIS SOFTWARE IS PROVIDED
 * BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package tc.de.krawallmann.twl;

import java.io.IOException;
import java.net.URL;

import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.GameState;
import org.newdawn.slick.state.StateBasedGame;

import de.matthiasmann.twl.GUI;
import de.matthiasmann.twl.Widget;
import de.matthiasmann.twl.renderer.Renderer;
import de.matthiasmann.twl.renderer.lwjgl.LWJGLRenderer;
import de.matthiasmann.twl.theme.ThemeManager;

/**
 * A StateBaseGame subclass with support for a TWL Ui per
 * org.newdawn.slick.state.
 * 
 * @author Matthias Mann
 */
public abstract class AbstractTWLStateBasedGame extends StateBasedGame {

	/** The empty root widget. */
	private transient final Widget emptyRootWidget;

	/** The gui. */
	private transient GUI gui;

	/** The gui initialized. */
	private transient boolean guiInitialized;

	private transient Input input;

	/** The renderer. */
	private transient LWJGLRenderer renderer;

	/**
	 * Instantiates a new abstract twl state based game.
	 * 
	 * @param name
	 *            the name
	 */
	protected AbstractTWLStateBasedGame(final String name) {
		super(name);
		emptyRootWidget = new Widget();
		emptyRootWidget.setTheme("");
	}

	/**
	 * Adds a new game org.newdawn.slick.state. This method is overriden to
	 * ensure that only instances of BasicTWLGameState are added.
	 * 
	 * @param state
	 *            the state
	 * @see StateBasedGame#addState(org.newdawn.slick.state.GameState)
	 */
	@Override
	public void addState(final GameState state) {
		if (!(state instanceof BasicTWLGameState)) {
			throw new IllegalArgumentException(
					"org.newdawn.slick.state must be a BasicTWLGameState");
		}
		super.addState(state);
	}

	/**
	 * Gets the gUI.
	 * 
	 * @return the gUI
	 */
	public GUI getGUI() {
		return gui;
	}

	/**
	 * Gets the renderer.
	 * 
	 * @return the renderer
	 */
	public LWJGLRenderer getRenderer() {
		return renderer;
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#inputEnded()
	 */
	@Override
	public void inputEnded() {
		gui.handleKeyRepeat();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#inputStarted()
	 */
	@Override
	public void inputStarted() {
		gui.updateTime();
		if (!Display.isActive()) {
			gui.clearKeyboardState();
			gui.clearMouseState();

			if (gui.getRootPane() instanceof RootPane) {
				((RootPane) gui.getRootPane()).keyboardFocusLost();
			}
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#keyPressed(int, char)
	 */
	@Override
	public void keyPressed(final int key, final char c) {// NOPMD
		gui.handleKey(key, c, true);
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#keyReleased(int, char)
	 */
	@Override
	public void keyReleased(final int key, final char c) {// NOPMD
		gui.handleKey(key, c, false);
		input.consumeEvent();
	}

	/**
	 * Make ui.
	 */
	public void makeUI() {
		if (gui != null) {
			gui.setRootPane(emptyRootWidget);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mouseClicked(int, int, int, int)
	 */
	@Override
	public void mouseClicked(final int button, final int x, final int y, final int clickCount) {// NOPMD
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mouseDragged(int, int, int, int)
	 */
	@Override
	public void mouseDragged(final int oldx, final int oldy, final int newX, final int newY) {
		mouseMoved(oldx, oldy, newX, newY);
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mouseMoved(int, int, int, int)
	 */
	@Override
	public void mouseMoved(final int oldX, final int oldY, final int newX, final int newY) {
		gui.handleMouse(newX, newY, -1, false);
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mousePressed(int, int, int)
	 */
	@Override
	public void mousePressed(final int button, final int x, final int y) {// NOPMD
		gui.handleMouse(x, y, button, true);
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mouseReleased(int, int, int)
	 */
	@Override
	public void mouseReleased(final int button, final int x, final int y) {// NOPMD
		gui.handleMouse(x, y, button, false);
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see org.newdawn.slick.util.InputAdapter#mouseWheelMoved(int)
	 */
	@Override
	public void mouseWheelMoved(final int change) {
		// Bugfix!
		if (change < 0) {
			gui.handleMouseWheel(-1);
		} else if (change > 0) {
			gui.handleMouseWheel(1);
		}
		input.consumeEvent();
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.newdawn.slick.state.StateBasedGame#render(org.newdawn.slick.GameContainer
	 * , org.newdawn.slick.Graphics)
	 */
	@Override
	public void render(final GameContainer container, final Graphics graphics)
			throws SlickException {// NOPMD
		preRenderState(container, graphics);

		if (leaveTransition != null) {// NOPMD
			leaveTransition.preRender(this, container, graphics);
		} else if (enterTransition != null) {
			enterTransition.preRender(this, container, graphics);
		}

		currentState.render(container, this, graphics);
		renderUI();

		if (leaveTransition != null) {// NOPMD
			leaveTransition.postRender(this, container, graphics);
		} else if (enterTransition != null) {
			enterTransition.postRender(this, container, graphics);
		}

		postRenderState(container, graphics);
	}

	/*
	 * (non-Javadoc)
	 * @see
	 * org.newdawn.slick.state.StateBasedGame#update(org.newdawn.slick.GameContainer
	 * , int)
	 */
	@Override
	public void update(final GameContainer container, final int delta) throws SlickException {
		preUpdateState(container, delta);
		if (leaveTransition != null) {
			leaveTransition.update(this, container, delta);
			if (leaveTransition.isComplete()) {
				makeUI();
				updateUI();
				currentState.leave(container, this);
				final GameState prevState = currentState;// NOPMD
				currentState = nextState;
				nextState = null;// NOPMD
				leaveTransition = null;// NOPMD
				currentState.enter(container, this);
				if (enterTransition == null) {
					currentState.enter(container, this);
				} else {
					enterTransition.init(currentState, prevState);
				}
			} else {
				return;// NOPMD
			}
		}
		updateUI();

		if (enterTransition != null) {
			enterTransition.update(this, container, delta);
			if (enterTransition.isComplete()) {
				enterTransition = null;// NOPMD
			} else {
				return;
			}
		}

		currentState.update(container, this, delta);

		postUpdateState(container, delta);
	}

	/**
	 * Update ui.
	 */
	public void updateUI() {
		if (gui != null) {
			gui.setSize();
			gui.handleTooltips();
			gui.updateTimers();
			gui.invokeRunables();
			gui.validateLayout();
			gui.setCursor();
		}
	}

	/**
	 * Implement this method and return the URL for the TWL theme.
	 * 
	 * @return the URL for the TWL theme. Must not be null.
	 */
	protected abstract URL getThemeURL();

	/**
	 * Initializes the gui.
	 * 
	 * @throws SlickException
	 *             the slick exception
	 */
	protected void initGUI() throws SlickException {
		GL11.glPushAttrib(GL11.GL_ALL_ATTRIB_BITS);
		try {
			renderer = new LWJGLRenderer();
			final ThemeManager theme = loadTheme(renderer);

			gui = new GUI(emptyRootWidget, renderer, null);
			gui.applyTheme(theme);

			input = getContainer().getInput();
		} catch (final Throwable e) {// NOPMD
			throw new SlickException("Could not initialize TWL GUI", e);
		} finally {
			GL11.glPopAttrib();
		}
	}

	/**
	 * Load theme.
	 * 
	 * @param renderer
	 *            the renderer
	 * @return the theme manager
	 * @throws IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected ThemeManager loadTheme(final Renderer renderer) throws IOException {// NOPMD
		final URL url = getThemeURL();
		assert url != null;
		return ThemeManager.createThemeManager(url, renderer);
	}

	/**
	 * Render ui.
	 */
	protected void renderUI() {
		if (gui != null) {
			gui.draw();
		}
	}

	/**
	 * Sets the root pane.
	 * 
	 * @param rootPane
	 *            the new root pane
	 * @throws SlickException
	 *             the slick exception
	 */
	protected void setRootPane(final RootPane rootPane) throws SlickException {
		if (!guiInitialized) {
			guiInitialized = true;
			initGUI();
		}
		if (gui != null) {
			gui.setRootPane(rootPane);
		}
	}
}
